/**
 * Project 68th
 */


#include "SearchEngineServer.h"
#include "KeyRecommanderTask.h"
#include "WebPageSearcherTask.h"
#include "LogUtils.h"

/**
 * SearchEngineServer implementation
 */


/**
 * @param threadNum
 * @param queSize
 * @param ip
 * @param port
 */
SearchEngineServer::SearchEngineServer(size_t threadNum, size_t queSize, const string& ip, unsigned short port) 
: _pool(threadNum,queSize)
, _server(ip,port)
{

}

SearchEngineServer::~SearchEngineServer() {

}

/**
 * @return void
 */
void SearchEngineServer::start() {
   _pool.start();

   using namespace std::placeholders;
   _server.setAllCallback(bind(&SearchEngineServer::OnNewConnection,this,_1),
                          bind(&SearchEngineServer::OnMessage,this,_1),
                          bind(&SearchEngineServer::OnClose,this,_1));

   _server.start();
}

/**
 * @return void
 */
void SearchEngineServer::stop() {
    _pool.stop();
    _server.stop();
}

void SearchEngineServer::OnNewConnection(const TcpConnectionPtr & con)
{
    LOG_INFO << "[TcpConnection] " << con->toString() << " has connected!";
}

void SearchEngineServer::OnMessage(const TcpConnectionPtr & con)
{
    Message msg = con->receive();

    // 判断任务的类型, 根据tag派发给不同的Task
    if(msg.tag == MessageTag::KeyRecommander){
        // 关键字推荐
        // KeyRecommanderTask
        KeyRecommanderTask kr_task(msg.value, con);
        _pool.addTask(std::bind(&KeyRecommanderTask::process, kr_task));
    
    }else if(msg.tag == MessageTag::WebPageSearcher){
        // 网页搜索
        // WebPageSearcherTask
        WebPageSearcherTask wps_task(msg.value, con);
        _pool.addTask(std::bind(&WebPageSearcherTask::process, wps_task));
    
    }else{
        // unknown tag
        return;
    }
}

void SearchEngineServer::OnClose(const TcpConnectionPtr & con)
{
    LOG_INFO << "[TcpConnection] " << con->toString() << " has closed!";
}
